package com.rainng.coursesystem.service.teacher;

import com.rainng.coursesystem.dao.CourseDAO;
import com.rainng.coursesystem.manager.teacher.CourseManager;
import com.rainng.coursesystem.model.entity.CourseEntity;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.model.vo.response.table.TeacherCourseItemVO;
import com.rainng.coursesystem.service.BaseService;
import com.rainng.coursesystem.service.UserService;
import com.rainng.coursesystem.util.LessonTimeConverter;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("teacher_courseService")
public class CourseService extends BaseService {
    private final CourseManager manager;
    private final UserService userService;
    private final LessonTimeConverter lessonTimeConverter;

    public CourseService(CourseManager manager, UserService userService, LessonTimeConverter lessonTimeConverter) {
        this.manager = manager;
        this.userService = userService;
        this.lessonTimeConverter = lessonTimeConverter;
    }

    public ResultVO list() {
        Integer teacherId = getUserId();
        List<CourseEntity> list =manager.listByTeacherId(teacherId);
        return result(list);
    }

    public ResultVO get(Integer id) {
        CourseEntity course = manager.getById(id);
        if (course == null) {
            return failedResult("课程不存在");
        }
        if (!course.getTeacherId().equals(getUserId())) {
            return failedResult("无权查看此课程");
        }
        return result(course);
    }

    public ResultVO create(CourseEntity entity) {
        entity.setTeacherId(getUserId());
        entity.setSelectedCount(0);
        manager.create(entity);
        return result("创建成功");
    }

    public ResultVO update(CourseEntity entity) {
        CourseEntity origin = manager.getById(entity.getId());
        if (origin == null) {
            return failedResult("课程不存在");
        }
        if (!origin.getTeacherId().equals(getUserId())) {
            return failedResult("无权修改此课程");
        }

        entity.setTeacherId(getUserId());
        entity.setSelectedCount(origin.getSelectedCount());
        manager.update(entity);
        return result("更新成功");
    }

    public ResultVO delete(Integer id) {
        CourseEntity course = manager.getById(id);
        if (course == null) {
            return failedResult("课程不存在");
        }
        if (!course.getTeacherId().equals(getUserId())) {
            return failedResult("无权删除此课程");
        }
        if (course.getSelectedCount() > 0) {
            return failedResult("该课程已有学生选课，无法删除");
        }

        manager.delete(id);
        return result("删除成功");
    }


}
